import os
import re

import numpy as np


def load_log(log_path):
    with open(log_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    return lines

def extract_iou_values(lines):
    iou_values = []
    pattern = re.compile(r'IoU (\d+\.\d+)')
    for line in lines:
        match = pattern.search(line)
        if match:
            iou = float(match.group(1))
            iou_values.append(iou)
    return iou_values

def count_errors(lines):
    error_count = 0
    pattern = re.compile(r'Error')
    for line in lines:
        match = pattern.search(line)
        if match:
            error_count += 1
    return error_count


if __name__ == '__main__':
    for name in os.listdir("./log"):
        log_path = os.path.join("./log", name, "info.log")
        lines = load_log(log_path)
        iou_values = np.array(extract_iou_values(lines))
        errors = count_errors(lines)
        
        miou = np.sum(iou_values) / (len(iou_values) - errors)
        ap50 = np.sum(iou_values >= 0.5) / (len(iou_values) - errors)
        ap75 = np.sum(iou_values >= 0.75) / (len(iou_values) - errors)
        ap90 = np.sum(iou_values >= 0.9) / (len(iou_values) - errors)

        print(f"{os.path.split(log_path)[0]}: mIoU: {miou:.4f} AP@50: {ap50:.4f} AP@75: {ap75:.4f} AP@90: {ap90:.4f}")


